#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import urllib.parse

from bottle import Bottle
from bottle import request, response

from conn.MyPagerFactory import MyPager

MemsubAdm = Bottle()


@MemsubAdm.hook('before_request')
def validate():
    REQUEST_METHOD = request.environ.get('REQUEST_METHOD')
    HTTP_ACCESS_CONTROL_REQUEST_METHOD = request.environ.get('HTTP_ACCESS_CONTROL_REQUEST_METHOD')
    if REQUEST_METHOD == 'OPTIONS' and HTTP_ACCESS_CONTROL_REQUEST_METHOD:
        request.environ['REQUEST_METHOD'] = HTTP_ACCESS_CONTROL_REQUEST_METHOD


@MemsubAdm.hook('after_request')
def enable_cors():
    response.headers['Access-Control-Allow-Origin'] = '*'  # 允许所有域名的请求
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT, HEAD, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'origin,content-type,accept,authorization,x-requested-with'
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers['Access-Control-Max-Age'] = 86400
    response.status = 200


class WebSubjectRoute:
    ERROR_CODE = {
        "80": "数据读取异常错误，请联系管理员",
        "99": "处理参数错误",
        "991": "处理参数错误, 请填写 %s",
        "100": "数据添加失败，请检查服务端日志",
        "102": "数据更新失败，请检查服务端日志",
        "103": "数据删除失败，请检查服务端日志",
        "104": "数据停止失败，请检查服务端日志",
        "105": "数据恢复失败，请检查服务端日志",
        "106": "数据激活失败，请检查服务端日志",
        "109": "数据不存在，数据处理失败",
    }
    SUBJECT_PARAM = [
        {"key": "name", "val": "姓名"},
        {"key": "phone", "val": "手机号"},
        {"key": "mail", "val": "电子邮箱"},
        {"key": "message", "val": "年龄"},
    ]

    webSubjetServiceImpl = None
    times_array = []

    def __init__(self, webSubjetService):
        WebSubjectRoute.webSubjetServiceImpl = webSubjetService
        return

    # 页面提交用户留言
    @staticmethod
    @MemsubAdm.post('/subject')
    def subject():
        if request.json is not None:
            data = request.json['data']
            decoded_string = urllib.parse.unquote(string=data, encoding='utf-8')
            str_times = request.json['times']
            if str_times in WebSubjectRoute.times_array:
                return
            else:
                WebSubjectRoute.times_array.append(str_times)
            data = json.loads(decoded_string)
            err = WebSubjectRoute.check_param_none(data)
            if err is None:
                db_data = {"subject_detl": decoded_string, "res": "", "status": 0}
                res = WebSubjectRoute.webSubjetServiceImpl.subject_message(subject=db_data)
                if res['code'] == 200:
                    return {'code': 200, 'data': res, 'message': ""}
                else:
                    return {'code': res['code'], 'data': res, 'message': WebSubjectRoute.ERROR_CODE["100"]}
            else:
                return err

    @staticmethod
    @MemsubAdm.get('/fetch')
    def fetch():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        res = WebSubjectRoute.webSubjetServiceImpl.fetch_subject(param=params)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': WebSubjectRoute.ERROR_CODE["99"]}
        view_list = res['data']
        _pages = MyPager.make_pager(id="table_subject_msg", res=view_list, page_size=int(params['pageSize']),
                                    data_total=res['total'], single_pager=False)
        return {'code': 200, 'data': _pages, 'message': ""}

    @staticmethod
    @MemsubAdm.get('/fetchOne')
    def fetch_one():
        params = {"key": str(request.params.key).replace(" ", ""),
                  "pageSize": request.params.pageSize,
                  "pageNum": request.params.pageNum}
        res = WebSubjectRoute.webSubjetServiceImpl.fetch_subject(param=params)
        if res["code"] != 200:
            return {'code': 99, 'data': None, 'message': WebSubjectRoute.ERROR_CODE["99"]}
        view_list = res['data']
        for _item in view_list:
            str_detail = _item['subject_detl']
            detail_obj = json.loads(str_detail)
            _item['uname'] = detail_obj['uname']
            _item['phone'] = detail_obj['phone']
            _item['mail'] = detail_obj['mail']
            _item['subject'] = detail_obj['subject']
        _pages = MyPager.make_pager(id="table_subject_msg", res=view_list, page_size=int(params['pageSize']),
                                    data_total=res['total'], single_pager=False)
        return {'code': 200, 'data': _pages, 'message': ""}

    @staticmethod
    @MemsubAdm.get('/read')
    def read():
        id = request.params.id
        return WebSubjectRoute.webSubjetServiceImpl.read_message(id=id)

    @staticmethod
    @MemsubAdm.get('/drop')
    def drop():
        id = request.params.id
        return WebSubjectRoute.webSubjetServiceImpl.drop_message(id=id)

    @staticmethod
    def check_param_none(val) -> {}:
        for item_index in range(len(WebSubjectRoute.SUBJECT_PARAM)):
            try:
                _check_item = WebSubjectRoute.SUBJECT_PARAM[item_index]
                _check_key = val[_check_item['key']]
                if isinstance(_check_key, str):
                    if _check_key is None or len(_check_key) == 0:
                        _str_error_message = WebSubjectRoute.ERROR_CODE["991"] % _check_item['val']
                        return {'code': 99, 'data': None, 'message': _str_error_message}
            except KeyError as e:
                continue
        return None
